<template>
  <div>
    <!-- 主内容区域 -->
    <div class="main-content">
      <div class="page-title">发布时间表</div>

      <!-- 发布时间表 -->
      <div class="publish-schedule">
        <div class="schedule-header">
          <div class="schedule-title">内容发布计划</div>
          <div class="schedule-actions">
            <el-button type="primary" @click="showPublishForm">
              <i class="fa-solid fa-plus"></i> 新建发布计划
            </el-button>
            <el-button type="text" @click="exportSchedule">
              <i class="fa-solid fa-download"></i> 导出
            </el-button>
            <el-button type="text" @click="importSchedule">
              <i class="fa-solid fa-upload"></i> 导入
            </el-button>
          </div>
        </div>

        <!-- 日历视图 -->
        <div class="calendar-container">
          <div class="calendar-header">
            <div class="calendar-title">{{ currentMonthName }} {{ currentYear }}</div>
            <div class="calendar-controls">
              <el-button size="mini" @click="prevMonth">
                <i class="fa-solid fa-chevron-left"></i>
              </el-button>
              <el-button size="mini" @click="today">
                <i class="fa-solid fa-calendar-day"></i> 今天
              </el-button>
              <el-button size="mini" @click="nextMonth">
                <i class="fa-solid fa-chevron-right"></i>
              </el-button>
            </div>
          </div>

          <div class="calendar-grid">
            <!-- 星期标题 -->
            <div class="calendar-day-header">周日</div>
            <div class="calendar-day-header">周一</div>
            <div class="calendar-day-header">周二</div>
            <div class="calendar-day-header">周三</div>
            <div class="calendar-day-header">周四</div>
            <div class="calendar-day-header">周五</div>
            <div class="calendar-day-header">周六</div>

            <!-- 日历格子 -->
            <div
                v-for="(day, index) in calendarDays"
                :key="index"
                class="calendar-day"
                :class="{
                'empty': !day.isCurrentMonth,
                'has-post': hasPosts(day.date),
                'is-today': isToday(day.date)
              }"
                @click="selectDate(day.date)"
            >
              <div class="calendar-day-number">{{ day.day }}</div>
              <div class="calendar-day-events">
                <div
                    v-for="(post, pIndex) in getPostsByDate(day.date)"
                    :key="pIndex"
                    class="calendar-day-event"
                    :title="post.title"
                >
                  {{ post.title }}
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 发布列表 -->
        <div class="publish-list">
          <div class="publish-list-header">
            <el-tabs v-model="activeTab" @tab-click="handleTabClick">
              <el-tab-pane label="全部" name="all"></el-tab-pane>
              <el-tab-pane label="待发布" name="pending"></el-tab-pane>
              <el-tab-pane label="已发布" name="published"></el-tab-pane>
              <el-tab-pane label="已取消" name="cancelled"></el-tab-pane>
            </el-tabs>
          </div>

          <div v-if="selectedDatePosts.length === 0" class="empty-state">
            <div class="empty-icon">
              <i class="fa-solid fa-calendar-xmark"></i>
            </div>
            <div class="empty-text">当前没有发布计划</div>
            <el-button type="primary" size="small" @click="showPublishForm">
              <i class="fa-solid fa-plus"></i> 添加发布计划
            </el-button>
          </div>

          <div v-else>
            <div
                v-for="(post, index) in filteredPosts"
                :key="index"
                class="publish-item"
            >
              <div class="publish-time">
                {{ formatDateTime(post.publishTime) }}
              </div>

              <div class="publish-content">
                <div class="publish-title">{{ post.title }}</div>
                <div class="publish-summary">{{ post.summary }}</div>
              </div>

              <div class="publish-status" :class="post.status">
                {{ getStatusText(post.status) }}
              </div>

              <div class="publish-actions">
                <el-button type="text" size="mini" @click="editPost(post.id)">
                  <i class="fa-solid fa-pencil"></i> 编辑
                </el-button>
                <el-button type="text" size="mini" @click="deletePost(post.id)">
                  <i class="fa-solid fa-trash"></i> 删除
                </el-button>
                <el-button type="text" size="mini" @click="previewPost(post.id)">
                  <i class="fa-solid fa-eye"></i> 预览
                </el-button>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 发布内容表单弹窗 -->
      <el-dialog v-model="publishFormVisible" title="发布内容" width="70%">
        <template #content>
          <div class="publish-form">
            <div class="form-section">
              <div class="form-title">基本信息</div>
              <el-form :model="newPost" label-width="80px">
                <el-form-item label="标题">
                  <el-input v-model="newPost.title" placeholder="请输入标题"></el-input>
                </el-form-item>

                <el-form-item label="分类">
                  <el-select v-model="newPost.category" placeholder="请选择分类">
                    <el-option v-for="item in categories" :key="item.value" :label="item.label"
                               :value="item.value"></el-option>
                  </el-select>
                </el-form-item>

                <el-form-item label="标签">
                  <el-input v-model="newPost.tags" placeholder="请输入标签，用逗号分隔"></el-input>
                </el-form-item>
              </el-form>
            </div>

            <div class="form-section">
              <div class="form-title">内容详情</div>
              <el-form :model="newPost">
                <el-form-item label="封面图">
                  <el-upload
                      class="upload-demo"
                      action="#"
                      :on-preview="handlePreview"
                      :on-remove="handleRemove"
                      :before-upload="beforeUpload"
                      :file-list="newPost.coverImage ? [newPost.coverImage] : []"
                      list-type="picture-card"
                  >
                    <i class="el-icon-plus"></i>
                  </el-upload>
                </el-form-item>

                <el-form-item label="内容">
                  <el-input type="textarea" v-model="newPost.content" rows="8" placeholder="请输入内容"></el-input>
                </el-form-item>
              </el-form>
            </div>

            <div class="form-section">
              <div class="form-title">发布设置</div>
              <el-form :model="newPost" label-width="80px">
                <el-form-item label="发布时间">
                  <el-date-picker
                      v-model="newPost.publishTime"
                      type="datetime"
                      placeholder="选择日期时间"
                      value-format="yyyy-MM-dd HH:mm:ss"
                  >
                  </el-date-picker>
                </el-form-item>

                <el-form-item label="状态">
                  <el-radio-group v-model="newPost.status">
                    <el-radio label="scheduled">定时发布</el-radio>
                    <el-radio label="published">立即发布</el-radio>
                    <el-radio label="draft">保存草稿</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-form>
            </div>

            <div class="publish-preview" v-if="newPost.title && newPost.content">
              <div class="form-title">预览</div>
              <div class="preview-card">
                <img v-if="newPost.coverImage" :src="newPost.coverImage.url" alt="封面图" class="preview-image">
                <div class="preview-title">{{ newPost.title }}</div>
                <div class="preview-content">{{ newPost.content.substring(0, 200) }}...</div>
              </div>
            </div>
          </div>
        </template>
        <template #footer>
          <div class="form-actions">
            <el-button @click="publishFormVisible = false">取消</el-button>
            <el-button type="primary" @click="savePost">保存</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script>

export default {
    name: "schedule-view",
  data() {
    return {
      activeMenu: 'publish-schedule',
      currentYear: new Date().getFullYear(),
      currentMonth: new Date().getMonth(),
      calendarDays: [],
      posts: [],
      selectedDate: null,
      activeTab: 'all',
      publishFormVisible: false,
      newPost: {
        id: null,
        title: '',
        category: '',
        tags: '',
        coverImage: null,
        content: '',
        publishTime: '',
        status: 'scheduled',
        summary: ''
      },
      categories: [
        {value: 'fashion', label: '时尚'},
        {value: 'beauty', label: '美妆'},
        {value: 'food', label: '美食'},
        {value: 'travel', label: '旅行'},
        {value: 'lifestyle', label: '生活方式'},
        {value: 'tech', label: '科技'}
      ]
    };
  },
  computed: {
    currentMonthName() {
      const months = ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'];
      return months[this.currentMonth];
    },
    selectedDatePosts() {
      if (!this.selectedDate) return [];
      return this.posts.filter(post =>
          post.publishTime.startsWith(this.selectedDate)
      );
    },
    filteredPosts() {
      if (this.activeTab === 'all') return this.selectedDatePosts;
      return this.selectedDatePosts.filter(post => post.status === this.activeTab);
    }
  },
  watch: {
    currentMonth() {
      this.generateCalendar();
    },
    currentYear() {
      this.generateCalendar();
    }
  },
  methods: {
    handleOpen() {
      // 处理侧边栏菜单展开事件
    },
    handleClose() {
      // 处理侧边栏菜单关闭事件
    },
    generateCalendar() {
      const firstDay = new Date(this.currentYear, this.currentMonth, 1);
      const lastDay = new Date(this.currentYear, this.currentMonth + 1, 0);
      const daysInMonth = lastDay.getDate();
      const startDay = firstDay.getDay();

      this.calendarDays = [];

      // 添加前一个月的空白格子
      for (let i = 0; i < startDay; i++) {
        this.calendarDays.push({
          day: '',
          date: null,
          isCurrentMonth: false
        });
      }

      // 添加当前月的日期
      for (let i = 1; i <= daysInMonth; i++) {
        const date = new Date(this.currentYear, this.currentMonth, i);
        this.calendarDays.push({
          day: i,
          date: this.formatDate(date),
          isCurrentMonth: true
        });
      }

      // 添加后一个月的空白格子
      const remaining = 42 - this.calendarDays.length;
      for (let i = 1; i <= remaining; i++) {
        this.calendarDays.push({
          day: '',
          date: null,
          isCurrentMonth: false
        });
      }
    },
    prevMonth() {
      if (this.currentMonth === 0) {
        this.currentYear--;
        this.currentMonth = 11;
      } else {
        this.currentMonth--;
      }
    },
    nextMonth() {
      if (this.currentMonth === 11) {
        this.currentYear++;
        this.currentMonth = 0;
      } else {
        this.currentMonth++;
      }
    },
    today() {
      const now = new Date();
      this.currentYear = now.getFullYear();
      this.currentMonth = now.getMonth();
      this.selectedDate = this.formatDate(now);
    },
    formatDate(date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    },
    formatDateTime(dateTime) {
      const date = new Date(dateTime);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}`;
    },
    hasPosts(date) {
      return this.posts.some(post => post.publishTime.startsWith(date));
    },
    getPostsByDate(date) {
      return this.posts.filter(post => post.publishTime.startsWith(date));
    },
    isToday(date) {
      const today = this.formatDate(new Date());
      return date === today;
    },
    selectDate(date) {
      this.selectedDate = date;
    },
    showPublishForm() {
      this.newPost = {
        id: null,
        title: '',
        category: '',
        tags: '',
        coverImage: null,
        content: '',
        publishTime: '',
        status: 'scheduled',
        summary: ''
      };
      this.publishFormVisible = true;
    },
    savePost() {
      if (this.newPost.id) {
        // 更新现有帖子
        const index = this.posts.findIndex(post => post.id === this.newPost.id);
        if (index > -1) {
          this.posts.splice(index, 1, {...this.newPost});
        }
      } else {
        // 创建新帖子
        this.newPost.id = Date.now();
        this.newPost.summary = this.newPost.content.substring(0, 100) + '...';
        this.posts.push({...this.newPost});
      }
      this.publishFormVisible = false;
    },
    editPost(postId) {
      const post = this.posts.find(post => post.id === postId);
      if (post) {
        this.newPost = {...post};
        this.publishFormVisible = true;
      }
    },
    deletePost(postId) {
      this.$confirm('确定要删除这个发布计划吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.posts = this.posts.filter(post => post.id !== postId);
      }).catch(() => {
        // 取消操作
      });
    },
    previewPost() {
      // 实现预览功能
    },
    handlePreview() {
      // 处理预览事件
    },
    handleRemove() {
      // 处理移除事件
      this.newPost.coverImage = null;
    },
    beforeUpload(file) {
      // 处理上传前的验证
      const isJPG = file.type === 'image/jpeg';
      const isPNG = file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG && !isPNG) {
        this.$message.error('上传封面图只能是 JPG/PNG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传封面图大小不能超过 2MB!');
      }
      return (isJPG || isPNG) && isLt2M;
    },
    getStatusText(status) {
      switch (status) {
        case 'pending':
          return '待发布';
        case 'published':
          return '已发布';
        case 'scheduled':
          return '定时发布';
        case 'cancelled':
          return '已取消';
        default:
          return status;
      }
    },
    handleTabClick() {
      // 处理标签切换事件
    },
    exportSchedule() {
      // 实现导出功能
    },
    importSchedule() {
      // 实现导入功能
    }
  },
  mounted() {
    this.generateCalendar();
    this.today();
    // 这里可以添加加载已有发布计划的逻辑
    // axios.get('/api/posts').then(response => {
    //   this.posts = response.data;
    // });
  }
};
</script>

<style scoped lang="scss">

/* 主内容区域 */

.page-title {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 20px;
}

/* 发布时间表相关样式 */
.publish-schedule {
  background-color: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  margin-bottom: 20px;
}

.schedule-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;
}

.schedule-title {
  font-size: 18px;
  font-weight: 500;
}

.schedule-actions {
  display: flex;
  gap: 10px;
}

/* 日历组件 */
.calendar-container {
  margin-bottom: 20px;
}

.calendar-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 10px;
}

.calendar-title {
  font-size: 16px;
  font-weight: 500;
}

.calendar-controls {
  display: flex;
  gap: 10px;
}

.calendar-grid {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  gap: 5px;
}

.calendar-day-header {
  text-align: center;
  padding: 8px;
  font-weight: 500;
}

.calendar-day {
  aspect-ratio: 1/1;
  border-radius: 8px;
  padding: 5px;
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
}

.calendar-day:hover {
  background-color: rgba(254, 44, 85, 0.05);
}

.calendar-day.empty {
  background-color: #f8f9fa;
  cursor: default;
}

.calendar-day.has-post {
  background-color: rgba(254, 44, 85, 0.1);
}

.calendar-day.is-today {
  border: 2px solid var(--primary-color);
}

.calendar-day-number {
  font-size: 14px;
  font-weight: 500;
  margin-bottom: 5px;
}

.calendar-day-events {
  display: flex;
  flex-direction: column;
  gap: 3px;
  font-size: 12px;
}

.calendar-day-event {
  padding: 2px 4px;
  border-radius: 4px;
  background-color: rgba(254, 44, 85, 0.2);
  color: var(--primary-color);
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 发布时间列表 */
.publish-list {
  margin-top: 20px;
}

.publish-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 16px;
  border-radius: 8px;
  margin-bottom: 10px;
  background-color: #f8f9fa;
  transition: all 0.3s ease;
}

.publish-item:hover {
  background-color: #f1f3f5;
}

.publish-time {
  font-weight: 500;
}

.publish-content {
  flex: 1;
  margin: 0 16px;
}

.publish-title {
  font-weight: 500;
  margin-bottom: 4px;
}

.publish-status {
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.publish-status.pending {
  background-color: rgba(255, 149, 0, 0.1);
  color: var(--warning-color);
}

.publish-status.published {
  background-color: rgba(76, 217, 100, 0.1);
  color: var(--success-color);
}

.publish-status.scheduled {
  background-color: rgba(51, 153, 255, 0.1);
  color: var(--info-color);
}

.publish-actions {
  display: flex;
  gap: 8px;
}

/* 发布内容表单 */
.publish-form {
  margin-top: 20px;
}

.form-section {
  margin-bottom: 20px;
}

.form-title {
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 12px;
}

.publish-preview {
  margin-top: 20px;
}

.preview-image {
  width: 100%;
  max-height: 300px;
  object-fit: cover;
  border-radius: 8px;
  margin-bottom: 10px;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 20px;
}

</style>
